package com.yuanzong.wuliu.service.admin.base;

import com.yuanzong.wuliu.common.exception.BusinessException;
import com.yuanzong.wuliu.common.utils.code.PhotoCodeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class AdminCodeService {

    public void photo(HttpServletRequest request, HttpServletResponse response, String photoCodeKey) throws Exception {
        // 整体参数验证
        if (StringUtils.isEmpty(photoCodeKey)) {
            throw new BusinessException("参数不能为空");
        }
        Map codeMap = PhotoCodeUtils.generateCaptcha();
        String value = codeMap.get(PhotoCodeUtils.CODE_VALUE).toString();
        // 保存验证码信息,存入Map
        PhotoCodeUtils.photoCodeMap.put(photoCodeKey, value);
        // 图片回显
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.getOutputStream().write((byte[]) codeMap.get(PhotoCodeUtils.CODE_IMAGE));
        response.getOutputStream().flush();
    }

}
